package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.domain.cluster.request.ClusterAppAssignMap;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 集群流控配置
 * @author admin
 */
@Component("clusterAppAssignNacosPublisher")
public class ClusterAppAssignNacosPublisher implements DynamicRulePublisher<List<ClusterAppAssignMap>> {

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<ClusterAppAssignMap>, String> converter;

    @Override
    public void publish(String appName, List<ClusterAppAssignMap> rules) throws Exception {
        AssertUtil.notEmpty(appName, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        configService.publishConfig(appName + NacosConfigUtil.CLUSTER_MAP_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, converter.convert(rules));
    }
}
